package com.hw.core.system.service;

import com.hw.core.system.controller.PublicController;
import com.hw.core.system.entity.Course;
import com.hw.core.system.entity.CourseType;
import com.hw.core.system.esRepository.CourseESRepository;
import com.hw.core.system.repository.CourseRepository;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class CourseESService {
    private static final Logger logger = LoggerFactory.getLogger( CourseESService.class );

    @Autowired
    private CourseESRepository courseESRepository;

    @Autowired
    private CourseRepository courseRepository;

    public void addAll() {
        List<Course> all = courseRepository.findAll();
        logger.info( "创建数据库课程索引" );
        for (Course course : all) {
            course.setAuthor( null );
            course.setCourseTypes( new ArrayList<CourseType>() );
            Course save = courseESRepository.save( course );
        }
    }

    public void deleteAll() {
        courseESRepository.deleteAll();
    }

    public Page<Course> find(String key, Integer page, Integer size) {
        QueryStringQueryBuilder builder = new QueryStringQueryBuilder( key );
        PageRequest pageRequest = new PageRequest( page - 1, size );
        return courseESRepository.search( builder, pageRequest );

    }

}
